<template>
  <el-form :model="form" ref="form" :rules="rules" class="form">
    <el-form-item class="form-item" prop="username">
      <el-input
        placeholder="用户名/手机"
        v-model="form.username"
        @focus="hideErrMsg('username')"
      ></el-input>
    </el-form-item>

    <el-form-item class="form-item" prop="password">
      <el-input
        placeholder="密码"
        type="password"
        v-model="form.password"
        @focus="hideErrMsg('password')"
      ></el-input>
    </el-form-item>

    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>

    <el-button class="submit" type="primary" @click="handleLoginSubmit"
      >登录</el-button
    >
  </el-form>
</template>

<script>
export default {
  props: ["url"],
  data() {
    return {
      // 表单数据
      form: {
        username: "13800138000",
        password: "123456"
      },
      // 表单规则
      rules: {
        username: [
          { min: 6, max: 11, message: "长度在 6 到 11个字符", trigger: "blur" }
        ],
        password: [
          { min: 6, max: 11, message: "长度在 6 到 11个字符", trigger: "blur" },
          {
            pattern: /^\d{6,11}$/,
            message: "密码由6~11位数字组成",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    // 提交登录
    handleLoginSubmit() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$axios({
              url: "/accounts/login",
              data: this.form,
              method: "post"
            }).then(res => {
              console.log(res.data);
              console.log('登陆成功')
              // 把用户存起来
              this.$store.commit('user/setUserInfo',res.data)
              // 回到首页
              if(this.$route.path=='/user'){
                this.$router.replace('/')
              }else{
                // 关闭登录框
                this.$emit('DialogClose')
              }
            });
          }
        });
      /* } */
    },

    //再次聚焦隐藏错误消息
    hideErrMsg(data) {
      this.$refs["form"].clearValidate(data);
    }
  }
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>
